package com.zlm.zy.zhoujuanjuan.a;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 创建时间: 2018/11/30 16:34
 * 作者: zhoujuanjuan
 * 描述: AES加密
 */
public class AESEncrypt {
  /**
   * AES转变
   * <p>法算法名称/加密模式/填充方式</p>
   * <p>加密模式有：电子密码本模式ECB、加密块链模式CBC、加密反馈模式CFB、输出反馈模式OFB</p>
   * <p>填充方式有：NoPadding、ZerosPadding、PKCS5Padding</p>
   */
  public static String AES_Transformation = "AES/ECB/PKCS5Padding";
  private static final String AES_Algorithm = "AES";
  /**
   * 设置加密字符集
   * 本例采用 UTF-8 字符集
   */
  private static final String CHARACTER = "UTF-8";

  /**
   * AES加密数据ToBase64字符串
   */
  public static String encryptAESToBase64(String sSrc, String sKey) {
    byte[] data = encrypt(sSrc, sKey);
    return EncodeUtils.base64Encode(data);
  }

  /**
   * Base64字符串ToAES加密数据
   */
  public static String decryptBase64ToAES(String sSrc, String sKey) {
    byte[] data = EncodeUtils.base64Decode(sSrc);
    return decrypt(data, sKey);
  }

  /**
   * AES加密  注：key一般为16字节为一块，如果不够16字节需要补位
   */
  public static byte[] encrypt(String sSrc, String sKey) {
    try {
      SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(CHARACTER), AES_Algorithm);
      Cipher cipher = Cipher.getInstance(AES_Transformation);//"算法/模式/补码方式"
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      byte[] encrypted = cipher.doFinal(sSrc.getBytes(CHARACTER));
      return encrypted;//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    } catch (Exception ex) {
      return null;
    }
  }

  /**
   * AES解密
   */
  public static String decrypt(byte[] sSrc, String sKey) {
    try {
      SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes(CHARACTER), AES_Algorithm);
      Cipher cipher = Cipher.getInstance(AES_Transformation);
      cipher.init(Cipher.DECRYPT_MODE, skeySpec);
      byte[] dncrypted = cipher.doFinal(sSrc);
      return new String(dncrypted, CHARACTER);
    } catch (Exception ex) {
      return null;
    }
  }

}
